﻿using BP.DA;
using BP.Difference;
using BP.En;
using BP.Port;
using BP.Sys;
using BP.WF.Data;
using BP.WF.Template;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BP.WF
{
    public class Install
    {
        /// <summary>
        /// 检查是否可以安装驰骋BPM系统
        /// </summary>
        /// <returns></returns>
        public static bool IsCanInstall()
        {
            if (SystemConfig.RunOnPlant.Equals("JFlow") == true)
            {
                if (SystemConfig.AppCenterDSN.Contains("/" + SystemConfig.AppCenterDBDatabase + "?") == false)
                    throw new Exception("数据库配置错误，配置的数据库名称必须包含在链接串里面。");
            }

            string sql = "";
            string errInfo = "";
            try
            {
                errInfo = " 当前用户没有[查询系统表]的权限. ";

                if (DBAccess.IsExitsObject("AA"))
                {
                    errInfo = " 当前用户没有[删除表]的权限. ";
                    sql = "DROP TABLE AA";
                    DBAccess.RunSQL(sql);
                }

                errInfo = " 当前用户没有[创建表]的权限. ";
                sql = "CREATE TABLE AA (OID int NOT NULL)"; //检查是否可以创建表.
                DBAccess.RunSQL(sql);

                errInfo = " 当前用户没有[插入数据]的权限. ";
                sql = "INSERT INTO AA (OID) VALUES(100)";
                DBAccess.RunSQL(sql);

                try
                {
                    //检查是否可以批量执行sql.
                    sql = "UPDATE AA SET OID=0 WHERE OID=1;UPDATE AA SET OID=0 WHERE OID=1;";
                    DBAccess.RunSQL(sql);
                }
                catch
                {
                    throw new Exception("err@需要让数据库链接支持批量执行SQL语句，请修改数据库链接配置：&allowMultiQueries=true");
                }

                errInfo = " 当前用户没有[update 表数据]的权限. ";
                sql = "UPDATE AA SET OID=101";
                DBAccess.RunSQL(sql);

                errInfo = " 当前用户没有[delete 表数据]的权限. ";
                sql = "DELETE FROM AA";
                DBAccess.RunSQL(sql);

                errInfo = " 当前用户没有[创建表主键]的权限. ";
                DBAccess.CreatePK("AA", "OID", BP.Difference.SystemConfig.AppCenterDBType);

                errInfo = " 当前用户没有[创建索引]的权限. ";
                DBAccess.CreatIndex("AA", "OID"); //可否创建索引.

                errInfo = " 当前用户没有[查询数据表]的权限. ";
                sql = "select * from AA "; //检查是否有查询的权限.
                DBAccess.RunSQLReturnTable(sql);

                errInfo = " 当前数据库设置区分了大小写，不能对大小写敏感，如果是mysql数据库请参考 https://blog.csdn.net/ccflow/article/details/100079825 ";
                sql = "select * from aa "; //检查是否区分大小写.
                DBAccess.RunSQLReturnTable(sql);

                if (DBAccess.IsExitsObject("AAVIEW"))
                {
                    errInfo = " 当前用户没有[删除视图]的权限. ";
                    sql = "DROP VIEW AAVIEW";
                    DBAccess.RunSQL(sql);
                }

                errInfo = " 当前用户没有[创建视图]的权限.";
                sql = "CREATE VIEW AAVIEW AS SELECT * FROM AA "; //检查是否可以创建视图.
                DBAccess.RunSQL(sql);

                errInfo = " 当前用户没有[删除视图]的权限.";
                sql = "DROP VIEW AAVIEW"; //检查是否可以删除视图.
                DBAccess.RunSQL(sql);

                errInfo = " 当前用户没有[删除表]的权限.";
                sql = "DROP TABLE AA"; //检查是否可以删除表.
                DBAccess.RunSQL(sql);

                if (BP.Difference.SystemConfig.AppCenterDBType == DBType.MySQL)
                {
                    try
                    {
                        sql = " set @@global.sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';";
                        DBAccess.RunSQL(sql);
                    }
                    catch
                    {
                    }
                }

                if (BP.Difference.SystemConfig.AppCenterDBDatabase.Contains("-") == true)
                    throw new Exception("err@数据库名称不能包含 '-' 号，您可以使用 '_' .");

                return true;
            }
            catch (Exception ex)
            {
                if (DBAccess.IsExitsObject("AA") == true)
                {
                    sql = "DROP TABLE AA";
                    DBAccess.RunSQL(sql);
                }

                if (DBAccess.IsExitsObject("AAVIEW") == true)
                {
                    sql = "DROP VIEW AAVIEW";
                    DBAccess.RunSQL(sql);
                }

                string info = "驰骋工作流引擎 - 检查数据库安装权限出现错误:";
                info += "\t\n1. 当前登录的数据库帐号，必须有创建、删除视图或者table的权限。";
                info += "\t\n2. 必须对表有增、删、改、查的权限。 ";
                info += "\t\n3. 必须有删除创建索引主键的权限。 ";
                info += "\t\n4. 我们建议您设置当前数据库连接用户为管理员权限。 ";
                info += "\t\n ccbpm检查出来的信息如下：" + errInfo;
                info += "\t\n etc: 数据库测试异常信息:" + ex.Message;
                throw new Exception("err@" + info);
                //  return false;
            }
        }

        /// <summary>
        /// 安装包
        /// </summary>
        /// <param name="lang">语言</param>
        /// <param name="demoType">0安装Demo, 1 不安装Demo.</param>
        public static void DoInstallDataBase(string lang, int demoType)
        {
            bool isInstallFlowDemo = true;
            if (demoType == 2)
                isInstallFlowDemo = false;

            #region 首先创建Port类型的表, 让admin登录.

            SFDBSrc sf = new SFDBSrc();
            sf.CheckPhysicsTable();

            FrmRB rb = new FrmRB();
            rb.CheckPhysicsTable();

            BP.Port.Emp portEmp = new BP.Port.Emp();
            portEmp.CheckPhysicsTable();

            BP.Port.Dept mydept = new BP.Port.Dept();
            mydept.CheckPhysicsTable();

            Station mySta = new Station();
            mySta.CheckPhysicsTable();

            StationType myStaType = new StationType();
            myStaType.CheckPhysicsTable();

            BP.Port.DeptEmp myde = new BP.Port.DeptEmp();
            myde.CheckPhysicsTable();

            BP.Port.DeptEmpStation mydes = new BP.Port.DeptEmpStation();
            mydes.CheckPhysicsTable();

            BP.WF.Port.WFEmp wfemp = new BP.WF.Port.WFEmp();
            wfemp.CheckPhysicsTable();

            if (SystemConfig.CCBPMRunModel != CCBPMRunModel.Single)
            {
                BP.WF.Port.AdminGroup.Org org = new Port.AdminGroup.Org();
                org.CheckPhysicsTable();

                BP.WF.Port.Admin2Group.OrgAdminer oa = new Port.Admin2Group.OrgAdminer();
                oa.CheckPhysicsTable();

                BP.WF.Template.FlowSort fs = new FlowSort();
                fs.CheckPhysicsTable();

                BP.WF.Template.SysFormTree ft = new SysFormTree();
                ft.CheckPhysicsTable();
            }

            if (DBAccess.IsExitsTableCol("WF_Emp", "StartFlows") == false)
            {
                string sql = "";
                //增加StartFlows这个字段
                switch (BP.Difference.SystemConfig.AppCenterDBType)
                {
                    case DBType.MSSQL:
                        sql = "ALTER TABLE WF_Emp ADD StartFlows Text DEFAULT  NULL";
                        break;
                    case DBType.Oracle:
                    case DBType.DM:
                    case DBType.KingBaseR3:
                    case DBType.KingBaseR6:
                    case DBType.GBASE8CByOracle:
                        sql = "ALTER TABLE  WF_EMP add StartFlows BLOB";
                        break;
                    case DBType.MySQL:
                        sql = "ALTER TABLE WF_Emp ADD StartFlows TEXT COMMENT '可以发起的流程'";
                        break;
                    case DBType.Informix:
                        sql = "ALTER TABLE WF_Emp ADD StartFlows VARCHAR(4000) DEFAULT  NULL";
                        break;
                    case DBType.PostgreSQL:
                    case DBType.UX:
                    case DBType.HGDB:
                        sql = "ALTER TABLE WF_Emp ADD StartFlows Text DEFAULT  NULL";
                        break;
                    default:
                        throw new Exception("@没有涉及到的数据库类型");
                }
                DBAccess.RunSQL(sql);
            }
            #endregion 首先创建Port类型的表.

            #region 3, 执行基本的 sql
            string sqlscript = "";

            BP.Port.Emp empGPM = new BP.Port.Emp();
            empGPM.CheckPhysicsTable();

            BP.Port.DeptEmp de = new BP.Port.DeptEmp();
            de.CheckPhysicsTable();


            if (DBAccess.IsExitsTableCol("Port_Emp", "Pass") == false)
            {
                if (BP.Difference.SystemConfig.AppCenterDBType == DBType.Oracle || DBAccess.AppCenterDBType == DBType.DM || DBAccess.AppCenterDBType == DBType.GBASE8CByOracle)
                    DBAccess.RunSQL("ALTER TABLE Port_Emp ADD Pass VARCHAR(90) DEFAULT '123' NULL ");
                else if (BP.Difference.SystemConfig.AppCenterDBType == DBType.PostgreSQL || BP.Difference.SystemConfig.AppCenterDBType == DBType.HGDB)
                    DBAccess.RunSQL("ALTER TABLE Port_Emp ADD Pass VARCHAR(90) DEFAULT '123' NULL ");
                else
                    DBAccess.RunSQL("ALTER TABLE Port_Emp ADD Pass NVARCHAR(90) DEFAULT '123' NULL ");
            }
            if (DBAccess.IsExitsTableCol("Port_Emp", "LeaderT") == false)
            {
                if (SystemConfig.AppCenterDBType == DBType.Oracle || DBAccess.AppCenterDBType == DBType.DM || DBAccess.AppCenterDBType == DBType.GBASE8CByOracle)
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Emp ADD LeaderT VARCHAR(300) DEFAULT '' NULL  ");
                }
                else if (SystemConfig.AppCenterDBType == DBType.PostgreSQL || SystemConfig.AppCenterDBType == DBType.HGDB)
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Emp ADD LeaderT VARCHAR(300) DEFAULT '' NULL   ");
                }
                else if (SystemConfig.AppCenterDBType == DBType.MSSQL)
                {

                    DBAccess.RunSQL("ALTER TABLE [dbo].[Port_Emp] ADD [LeaderT] nvarchar(300)  DEFAULT ''  NULL");

                    //添加字段注释
                    DBAccess.RunSQL("EXEC sp_addextendedproperty 'MS_Description', N'直接主管','SCHEMA', N'dbo','TABLE', N'Port_Emp','COLUMN', N'LeaderT'");
                }
                // 处理人大金仓字段问题
                else if (SystemConfig.AppCenterDBType == DBType.KingBaseR6)
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Emp ADD LeaderT NVARCHAR(300) DEFAULT '' NULL");
                    //添加字段注释
                    DBAccess.RunSQL("COMMENT ON COLUMN Port_Emp.LeaderT IS '直接主管'");
                }
                else
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Emp ADD LeaderT NVARCHAR(300) DEFAULT '' NULL  ");
                }
            }
            if (DBAccess.IsExitsTableCol("Port_Dept", "LinkMan") == false)
            {
                if (SystemConfig.AppCenterDBType == DBType.Oracle || DBAccess.AppCenterDBType == DBType.DM || DBAccess.AppCenterDBType == DBType.GBASE8CByOracle)
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD LinkMan VARCHAR(50) DEFAULT '' NULL  ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjNo VARCHAR(50) DEFAULT '' NULL   ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjName VARCHAR(50) DEFAULT '' NULL  ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjShortName VARCHAR(50) DEFAULT '' NULL ");
                }
                else if (SystemConfig.AppCenterDBType == DBType.PostgreSQL || SystemConfig.AppCenterDBType == DBType.HGDB)
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD LinkMan VARCHAR(50) DEFAULT '' NULL  ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjNo VARCHAR(50) DEFAULT '' NULL  ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjName VARCHAR(50) DEFAULT '' NULL   ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjShortName VARCHAR(50) DEFAULT ''   ");
                }
                else if (SystemConfig.AppCenterDBType == DBType.MSSQL)
                {
                    DBAccess.RunSQL("ALTER TABLE [dbo].[Port_Dept] ADD [LinkMan] nvarchar(50) DEFAULT '' NULL ");
                    DBAccess.RunSQL("EXEC sp_addextendedproperty 'MS_Description', N'部门联络员', 'SCHEMA', N'dbo','TABLE', N'Port_Dept','COLUMN', N'LinkMan'");

                    DBAccess.RunSQL("ALTER TABLE [dbo].[Port_Dept] ADD [PrjNo] nvarchar(50) DEFAULT '' NULL ");
                    DBAccess.RunSQL("EXEC sp_addextendedproperty 'MS_Description', N'项目编号', 'SCHEMA', N'dbo','TABLE', N'Port_Dept','COLUMN', N'PrjNo'");

                    //添加注释
                    DBAccess.RunSQL("ALTER TABLE [dbo].[Port_Dept] ADD [PrjName] nvarchar(50) DEFAULT '' NULL ");
                    DBAccess.RunSQL("EXEC sp_addextendedproperty 'MS_Description', N'项目名称', 'SCHEMA', N'dbo','TABLE', N'Port_Dept','COLUMN', N'PrjName'");

                    DBAccess.RunSQL("ALTER TABLE [dbo].[Port_Dept] ADD [PrjShortName] nvarchar(50) DEFAULT '' NULL ");
                    DBAccess.RunSQL("EXEC sp_addextendedproperty 'MS_Description', N'项目简称', 'SCHEMA', N'dbo','TABLE', N'Port_Dept','COLUMN', N'PrjShortName'");

                }
                // 处理人大金仓字段问题
                else if (SystemConfig.AppCenterDBType == DBType.KingBaseR6)
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD LinkMan NVARCHAR(50) DEFAULT '' NULL  ");
                    DBAccess.RunSQL("COMMENT ON COLUMN Port_Dept.LinkMan IS '部门联络员'");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjNo NVARCHAR(50) DEFAULT '' NULL ");
                    DBAccess.RunSQL("COMMENT ON COLUMN Port_Dept.PrjNo IS '项目编号'");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjName NVARCHAR(50) DEFAULT '' NULL ");
                    DBAccess.RunSQL("COMMENT ON COLUMN Port_Dept.PrjName IS '项目名称'");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjShortName NVARCHAR(50) DEFAULT '' NULL ");
                    DBAccess.RunSQL("COMMENT ON COLUMN Port_Dept.PrjShortName IS '项目简称'");
                }
                else
                {
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD LinkMan NVARCHAR(50) DEFAULT '' NULL COMMENT '部门联络员' ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjNo NVARCHAR(50) DEFAULT '' NULL COMMENT '项目编号' ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjName NVARCHAR(50) DEFAULT '' NULL COMMENT '项目名称' ");
                    DBAccess.RunSQL("ALTER TABLE Port_Dept ADD PrjShortName NVARCHAR(50) DEFAULT '' NULL COMMENT '项目简称' ");
                }
            }
            //初始化数据
            sqlscript = BP.Difference.SystemConfig.CCFlowAppPath + "WF/Data/Install/SQLScript/Port_Inc_CH_RunModel_" + (int)SystemConfig.CCBPMRunModel + ".sql";
            DBAccess.RunSQLScript(sqlscript);


            if (SystemConfig.CCBPMRunModel == CCBPMRunModel.Single)
            {
                BP.Port.Emp empAdmin = new Emp("admin");
                BP.Web.WebUser.SignInOfGener(empAdmin);
            }

            if (SystemConfig.CCBPMRunModel == CCBPMRunModel.SAAS)
            {
                BP.WF.Dev2Interface.Port_Login("admin", "100", null);
            }

            if (SystemConfig.CCBPMRunModel == CCBPMRunModel.GroupInc)
            {
                BP.WF.Dev2Interface.Port_Login("admin", "100", null);
            }
            #endregion 执行基本的 sql

            ArrayList al = null;
            string info = "BP.En.Entity";
            al = BP.En.ClassFactory.GetObjects(info);

            #region 先创建表，否则列的顺序就会变化.
            FlowExt fe = new FlowExt();
            fe.CheckPhysicsTable();

            NodeExt ne = new NodeExt();
            ne.CheckPhysicsTable();

            MapDtl mapdtl = new MapDtl();
            mapdtl.CheckPhysicsTable();

            MapData mapData = new MapData();
            mapData.CheckPhysicsTable();

            SysEnum sysenum = new SysEnum();
            sysenum.CheckPhysicsTable();

            BP.WF.Template.NodeWorkCheck fwc = new NodeWorkCheck();
            fwc.CheckPhysicsTable();

            MapAttr attr = new MapAttr();
            attr.CheckPhysicsTable();

            GenerWorkFlow gwf = new GenerWorkFlow();
            gwf.CheckPhysicsTable();


            #endregion 先创建表，否则列的顺序就会变化.

            #region 1, 创建or修复表
            foreach (Object obj in al)
            {
                Entity en = null;
                en = obj as Entity;
                if (en == null)
                    continue;

                //获得类名.
                string clsName = en.ToString();
                if (DataType.IsNullOrEmpty(clsName) == true)
                    continue;

                if (clsName.Contains("FlowSheet") == true)
                    continue;
                if (clsName.Contains("NodeSheet") == true)
                    continue;
                if (clsName.Contains("FlowFormTree") == true)
                    continue;

                //不安装CCIM的表.
                if (clsName.Contains("BP.CCIM"))
                    continue;

                //抽象的类不允许创建表.
                switch (clsName.ToUpper())
                {
                    case "BP.WF.STARTWORK":
                    case "BP.WF.WORK":
                    case "BP.WF.GESTARTWORK":
                    case "BP.EN.GENONAME":
                    case "BP.EN.GETREE":
                    case "BP.WF.GERpt":
                    case "BP.WF.GEENTITY":
                    case "BP.SYS.TSENTITYNONAME":
                        continue;
                    default:
                        break;
                }

                if (isInstallFlowDemo == false)
                {
                    /*如果不安装demo.*/
                    if (clsName.Contains("BP.CN")
                        || clsName.Contains("BP.Demo"))
                        continue;
                }

                string table = null;
                try
                {
                    table = en.EnMap.PhysicsTable;
                    if (table == null)
                        continue;
                }
                catch
                {
                    continue;
                }

                try
                {
                    switch (table)
                    {
                        case "WF_EmpWorks":
                        case "WF_GenerEmpWorkDtls":
                        case "WF_GenerEmpWorks":
                            continue;
                        case "Sys_Enum":
                            en.CheckPhysicsTable();
                            break;
                        default:
                            en.CheckPhysicsTable();
                            break;
                    }
                    en.CheckPhysicsTable();
                }
                catch
                {
                }
            }
            #endregion 修复

            #region 2, 注册枚举类型 SQL
            // 2, 注册枚举类型。
            BP.Sys.XML.EnumInfoXmls xmls = new BP.Sys.XML.EnumInfoXmls();
            xmls.RetrieveAll();
            foreach (BP.Sys.XML.EnumInfoXml xml in xmls)
            {
                BP.Sys.SysEnums ses = new BP.Sys.SysEnums();
                int count = ses.RetrieveByAttr(SysEnumAttr.EnumKey, xml.Key);
                if (count > 0)
                    continue;
                ses.RegIt(xml.Key, xml.Vals);
            }
            #endregion 注册枚举类型

            #region 2.1 重新构建视图.
            ReCreateView();
            #endregion 2.1 重新构建视图

            #region 5, 初始化数据.
          
            if (DBAccess.IsExitsObject("Demo_BanJi") == false)
            {
                sqlscript = "CREATE TABLE Demo_BanJi( ";
                sqlscript += "No varchar(20),";
                sqlscript += "Name varchar(50),";
                sqlscript += "BZR varchar(100)";
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }

            if (DBAccess.IsExitsObject("Demo_Student") == false)
            {
                sqlscript = "CREATE TABLE Demo_Student( ";
                sqlscript += "No varchar(50),";
                sqlscript += "Name varchar(50),";
                sqlscript += "PWD varchar(50),";
                sqlscript += "Addr varchar(50),";
                sqlscript += "Tel varchar(50),";
                sqlscript += "Email varchar(50),";
                sqlscript += "FK_BanJi varchar(50),";
                if (SystemConfig.AppCenterDBType == DBType.PostgreSQL)
                {
                    sqlscript += "Age integer,";
                    sqlscript += "XB integer,";
                    sqlscript += "ZZMM integer,";
                }
                else
                {
                    sqlscript += "Age int,";
                    sqlscript += "XB int,";
                    sqlscript += "ZZMM int";
                }
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }
            if (DBAccess.IsExitsObject("Demo_KeMu") == false)
            {
                sqlscript = "CREATE TABLE Demo_KeMu( ";
                sqlscript += "No varchar(80),";
                sqlscript += "Name varchar(50)";
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }
            if (DBAccess.IsExitsObject("Demo_PQ") == false)
            {
                sqlscript = "CREATE TABLE Demo_PQ( ";
                sqlscript += "No varchar(100),";
                sqlscript += "Name varchar(50)";
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }
            if (DBAccess.IsExitsObject("Demo_ShengFen") == false)
            {
                sqlscript = "CREATE TABLE Demo_ShengFen( ";
                sqlscript += "No varchar(100),";
                sqlscript += "Name varchar(100),";
                sqlscript += "Names varchar(100),";
                sqlscript += "JC varchar(50),";
                sqlscript += "FK_PQ varchar(50)";
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }
            if (DBAccess.IsExitsObject("Demo_City") == false)
            {
                sqlscript = "CREATE TABLE Demo_City( ";
                sqlscript += "No varchar(80),";
                sqlscript += "Name varchar(100),";
                sqlscript += "Names varchar(100),";
                if (SystemConfig.AppCenterDBType == DBType.PostgreSQL)
                {
                    sqlscript += "Grade integer,";
                }
                else
                {
                    sqlscript += "Grade int,";
                }
                sqlscript += "ShengFen varchar(100),";
                sqlscript += "FK_PQ varchar(100)";
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }
            if (DBAccess.IsExitsObject("Demo_Product") == false)
            {
                sqlscript = "CREATE TABLE Demo_Product( ";
                sqlscript += "No varchar(100),";
                sqlscript += "Name varchar(100),";
                sqlscript += "GuiGe varchar(100)"; //规格.
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }
            if (DBAccess.IsExitsObject("Demo_Customer") == false)
            {
                sqlscript = "CREATE TABLE Demo_Customer( ";
                sqlscript += "No varchar(100),";
                sqlscript += "Name varchar(100),";
                sqlscript += "Linker varchar(100),";
                sqlscript += "Tel varchar(100),";
                sqlscript += "Addr varchar(100),";
                sqlscript += "RDT varchar(100)";
                sqlscript += ") ";
                DBAccess.RunSQL(sqlscript);
            }
            //  BP.dEMO.
            sqlscript = BP.Difference.SystemConfig.PathOfData + "Install/SQLScript/InitPublicData.sql";
            DBAccess.RunSQLScript(sqlscript);
            
            #endregion 初始化数据

            #region 6, 生成临时的 wf_emp 数据。
            if (isInstallFlowDemo == true)
            {
                BP.Port.Emps emps = new BP.Port.Emps();
                emps.RetrieveAllFromDBSource();
                int i = 0;
                foreach (BP.Port.Emp emp in emps)
                {
                    i++;
                    BP.WF.Port.WFEmp wfEmp = new BP.WF.Port.WFEmp();
                    wfEmp.Copy(emp);
                    wfEmp.No = emp.UserID;

                    /* if (wfEmp.Email.Length == 0)
                         wfEmp.Email = emp.UserID + "@ccbpm.cn";*/

                    if (wfEmp.Tel.Length == 0)
                        wfEmp.Tel = "82374939-6" + i.ToString().PadLeft(2, '0');

                    if (wfEmp.IsExits)
                        wfEmp.Update();
                    else
                        wfEmp.Insert();
                }

                // 生成简历数据.
                foreach (BP.Port.Emp emp in emps)
                {
                    for (int myIdx = 0; myIdx < 6; myIdx++)
                    {
                        string sql = "";
                        sql = "INSERT INTO Demo_Resume (OID,RefPK,NianYue,GongZuoDanWei,ZhengMingRen,BeiZhu,QT) ";
                        sql += "VALUES(" + DBAccess.GenerOID("Demo_Resume") + ",'" + emp.UserID + "','200" + myIdx + "-01','成都.驰骋" + myIdx + "公司','张三','表现良好','其他-" + myIdx + "无')";
                        DBAccess.RunSQL(sql);
                    }
                }

                DataTable dtStudent = DBAccess.RunSQLReturnTable("SELECT No FROM Demo_Student");
                foreach (DataRow dr in dtStudent.Rows)
                {
                    string no = dr[0].ToString();
                    for (int myIdx = 0; myIdx < 6; myIdx++)
                    {
                        string sql = "";
                        sql = "INSERT INTO Demo_Resume (OID,RefPK,NianYue,GongZuoDanWei,ZhengMingRen,BeiZhu,QT) ";
                        sql += "VALUES(" + DBAccess.GenerOID("Demo_Resume") + ",'" + no + "','200" + myIdx + "-01','成都.驰骋" + myIdx + "公司','张三','表现良好','其他-" + myIdx + "无')";
                        DBAccess.RunSQL(sql);
                    }
                }
                GenerWorkFlowViewNY ny = new GenerWorkFlowViewNY();
                ny.CheckPhysicsTable();
                // 生成年度月份数据.
                string sqls = "";
                DateTime dtNow = DateTime.Now;
                for (int num = 0; num < 12; num++)
                {
                    sqls = "@ INSERT INTO Pub_NY (No,Name) VALUES ('" + dtNow.ToString("yyyy-MM") + "','" + dtNow.ToString("yyyy-MM") + "')  ";
                    dtNow = dtNow.AddMonths(1);
                }
                DBAccess.RunSQLs(sqls);
            }
            #endregion 初始化数据

            #region 7, 装载 demo.flow
            if (isInstallFlowDemo == true && SystemConfig.CCBPMRunModel == CCBPMRunModel.Single)
            {
                BP.Port.Emp emp = new BP.Port.Emp("admin");
                BP.Web.WebUser.SignInOfGener(emp);
                BP.Sys.Base.Glo.WriteLineInfo("开始装载模板...");
                string msg = "";

                //装载数据模版.
                BP.WF.DTS.LoadTemplete l = new BP.WF.DTS.LoadTemplete();
                msg = l.Do() as string;
            }

            if (isInstallFlowDemo == false && SystemConfig.CCBPMRunModel == CCBPMRunModel.Single)
            {
                //创建一个空白的流程，不然，整个结构就出问题。
                //    FlowSorts fss = new FlowSorts();
                // fss.RetrieveAll();
                //  fss.Delete();
                DBAccess.RunSQL("DELETE FROM WF_FlowSort ");
                FlowSort fs = new FlowSort();
                fs.Name = "流程树";
                fs.No = "1";
                fs.ParentNo = "0";
                fs.Insert();

                fs = new FlowSort();
                fs.No = "101";
                fs.ParentNo = "1";
                fs.Name = "日常办公类";
                fs.Insert();

                //加载一个模版,不然用户不知道如何新建流程.
                BP.WF.Template.TemplateGlo.LoadFlowTemplate(fs.No, BP.Difference.SystemConfig.PathOfData + "Install/QingJiaFlowDemoInit.xml",
                    ImpFlowTempleteModel.AsTempleteFlowNo);

                Flow fl = new Flow("001");
                fl.DoCheck(); //做一下检查.

                fs.No = "102";
                fs.ParentNo = "1";
                fs.Name = "财务类";
                fs.Insert();

                fs.No = "103";
                fs.ParentNo = "1";
                fs.Name = "人力资源类";
                fs.Insert();

                DBAccess.RunSQL("DELETE FROM Sys_FormTree ");
                SysFormTree ftree = new SysFormTree();
                ftree.Name = "表单树";
                ftree.No = "1";
                ftree.ParentNo = "0";
                ftree.Insert();

                SysFormTree subFrmTree = new SysFormTree();
                subFrmTree.Name = "流程独立表单";
                subFrmTree.ParentNo = "1";
                subFrmTree.No = "101";
                subFrmTree.Insert();

                subFrmTree = new SysFormTree(); ;
                subFrmTree.No = "102";
                subFrmTree.Name = "常用信息管理";
                subFrmTree.ParentNo = "1";
                subFrmTree.Insert();

                subFrmTree = new SysFormTree(); ;
                subFrmTree.Name = "常用单据";
                subFrmTree.No = "103";
                subFrmTree.ParentNo = "1";
                subFrmTree.Insert();
            }
            #endregion 装载demo.flow

            #region 增加图片签名
            if (isInstallFlowDemo == true)
            {
                try
                {
                    //增加图片签名
                    BP.WF.DTS.GenerSiganture gs = new BP.WF.DTS.GenerSiganture();
                    gs.Do();
                }
                catch
                {
                }
            }
            #endregion 增加图片签名.

            //生成拼音，以方便关键字查找.
            BP.WF.DTS.GenerPinYinForEmp pinyin = new BP.WF.DTS.GenerPinYinForEmp();
            pinyin.Do();

            #region 执行补充的sql, 让外键的字段长度都设置成100.
            DBAccess.RunSQL("UPDATE Sys_MapAttr SET maxlen=100 WHERE LGType=2 AND MaxLen<100");
            DBAccess.RunSQL("UPDATE Sys_MapAttr SET maxlen=100 WHERE KeyOfEn='FK_Dept'");
            #endregion 执行补充的sql, 让外键的字段长度都设置成100.

            #region 如果是第一次运行，就执行检查。
            if (isInstallFlowDemo == true)
            {
                Flows fls = new Flows();
                fls.RetrieveAllFromDBSource();
                foreach (Flow fl in fls)
                {
                    try
                    {
                        fl.DoCheck();
                    }
                    catch (Exception ex)
                    {
                        BP.DA.Log.DebugWriteError(ex.Message);
                    }
                }
            }
            #endregion 如果是第一次运行，就执行检查。

            #region 增加大文本字段列.
            try
            {
                if (DBAccess.IsExitsTableCol("Sys_MapData", "HtmlTemplateFile") == false)
                {
                    string sql = "ALTER TABLE Sys_MapData ADD  HtmlTemplateFile TEXT ";
                    DBAccess.RunSQL(sql);
                }
                DBAccess.GetBigTextFromDB("Sys_MapData", "No", "001", "HtmlTemplateFile");
            }
            catch (Exception e)
            {
                throw new Exception("err@增加大文本字段列时出现异常;@异常信息:" + e.Message);
            }
            #endregion 增加大文本字段列.

            #region 检查工作处理器的ShiftTo和ShiftNote字段是否存在
            try
            {
                if (DBAccess.IsExitsTableCol("WF_WorkOpt", "ShiftTo") == false)
                {
                    string sql = "ALTER TABLE WF_WorkOpt ADD  ShiftTo VARCHAR(100) ";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("WF_WorkOpt", "ShiftNote") == false)
                {
                    string sql = "ALTER TABLE WF_WorkOpt ADD  ShiftNote  text ";
                    DBAccess.RunSQL(sql);
                }
            }
            catch (Exception e)
            {
                throw new Exception("err@检查ShiftTo和ShiftNote字段时出现异常;@异常信息:" + e.Message);
            }
            #endregion 检查工作处理器的ShiftTo和ShiftNote字段是否存在

            #region 检查菜单表的UrlPath，path，Alias，IframeOpenType等字段是否存在
            try
            {
                if (DBAccess.IsExitsTableCol("GPM_Menu", "UrlPath") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  UrlPath VARCHAR(500)";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("GPM_Menu", "path") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  path VARCHAR(50)";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("GPM_Menu", "Alias") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  Alias VARCHAR(500)";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("GPM_Menu", "IframeOpenType") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  IframeOpenType VARCHAR(50)";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("GPM_Menu", "IframeOpenTypeT") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  IframeOpenTypeT VARCHAR(200) ";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("GPM_Menu", "IframeOpenTypeT") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  IframeOpenTypeT VARCHAR(200) ";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("GPM_Menu", "ModuleNoT") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  ModuleNoT VARCHAR(200)";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("GPM_Menu", "EnName") == false)
                {
                    string sql = "ALTER TABLE GPM_Menu ADD  EnName VARCHAR(300) ";
                    DBAccess.RunSQL(sql);
                }
            }
            catch (Exception e)
            {
                throw new Exception("err@检查菜单表的字段时出现异常;@异常信息:" + e.Message);
            }
            #endregion 检查菜单表的UrlPath，path，Alias，IframeOpenType等字段是否存在

            #region 检查表单树的字段是否存在
            try
            {
                if (DBAccess.IsExitsTableCol("Sys_FormTree", "ShortName") == false)
                {
                    string sql = "ALTER TABLE Sys_FormTree ADD  ShortName VARCHAR(200)";
                    DBAccess.RunSQL(sql);
                }
                if (DBAccess.IsExitsTableCol("Sys_FormTree", "DomainExt") == false)
                {
                    string sql = "ALTER TABLE Sys_FormTree ADD  DomainExt  VARCHAR(100) ";
                    DBAccess.RunSQL(sql);
                }
            }
            catch (Exception e)
            {
                throw new Exception("err@检查表单树的字段时出现异常;@异常信息:" + e.Message);
            }

            #endregion 检查表单树的字段是否存在

            #region 检查流程类别表的字段是否存在
            try
            {
                if (DBAccess.IsExitsTableCol("WF_FlowSort", "DirType") == false)
                {
                    string sql = "ALTER TABLE WF_FlowSort ADD  DirType Int";
                    DBAccess.RunSQL(sql);
                }
            }
            catch (Exception e)
            {
                throw new Exception("err@检查流程类别表的字段时出现异常;@异常信息:" + e.Message);
            }
            #endregion 检查流程类别表的字段是否存在

            #region 检查表单共享、流程共享字段是否存在
            try
            {
                //流程共享
                if (DBAccess.IsExitsTableCol("WF_Flow", "ShareSln") == false)
                {
                    string sql = "ALTER TABLE WF_Flow ADD  ShareSln Int ";
                    DBAccess.RunSQL(sql);
                }
                //表单共享
                if (DBAccess.IsExitsTableCol("Sys_MapData", "ShareSln") == false)
                {
                    string sql = "ALTER TABLE Sys_MapData ADD  ShareSln Int";
                    DBAccess.RunSQL(sql);
                }
                //显示列
                if (DBAccess.IsExitsTableCol("Sys_MapData", "ShowColModel") == false)
                {
                    string sql = "ALTER TABLE Sys_MapData ADD  ShowColModel Int ";
                    DBAccess.RunSQL(sql);
                }
            }
            catch (Exception e)
            {
                throw new Exception("err@检查表单共享、流程共享字段时出现异常;@异常信息:" + e.Message);
            }
            #endregion 检查表单共享、流程共享字段是否存在

            #region 检查SQL、JS、TS字段是否存在
            try
            {
                //SQL脚本内容
                if (DBAccess.IsExitsTableCol("Frm_Method", "SQLScript") == false)
                {
                    string sql = "ALTER TABLE Frm_Method ADD  SQLScript TEXT ";
                    DBAccess.RunSQL(sql);
                }
                //JS脚本内容
                if (DBAccess.IsExitsTableCol("Frm_Method", "JSScript") == false)
                {
                    string sql = "ALTER TABLE Frm_Method ADD  JSScript TEXT ";
                    DBAccess.RunSQL(sql);
                }
                //TS脚本内容
                if (DBAccess.IsExitsTableCol("Frm_Method", "TSScript") == false)
                {
                    string sql = "ALTER TABLE Frm_Method ADD  TSScript TEXT ";
                    DBAccess.RunSQL(sql);
                }
                //执行按钮
                if (DBAccess.IsExitsTableCol("Frm_Method", "BtnDoneText") == false)
                {
                    string sql = "ALTER TABLE Frm_Method ADD  BtnDoneText VARCHAR(100) ";
                    DBAccess.RunSQL(sql);
                }
            }
            catch (Exception e)
            {
                throw new Exception("err@检查检查SQL、JS、TS字段时出现异常;@异常信息:" + e.Message);
            }
            #endregion 检查SQL、JS、TS字段是否存在

            #region 检查WF_Node
            try
            {
                if (DBAccess.IsExitsTableCol("WF_Node", "CancelNodes") == false)
                {
                    string sql = "ALTER TABLE WF_Node ADD  CancelNodes VARCHAR(200) ";
                    DBAccess.RunSQL(sql);
                }
            }
            catch (Exception e)
            {
                throw new Exception("err@检查WF_Node的字段时出现异常;@异常信息:" + e.Message);
            }

            #endregion 检查WF_Node

            #region 处理密码加密.
            string pass = SystemConfig.UserDefaultPass;
            Object type = SystemConfig.GetIsPasswordEncryptionType();
            String key = SystemConfig.GetIsEncryptionKey();
            //BCrypt加密类型
            if (type != null && type.ToString().Equals("2"))
            {
                pass = BP.Tools.Cryptography.HashPassword(pass);
            }
            //MD5加密类型
            if (type != null && type.ToString().Equals("1"))
            {
                pass = BP.Tools.Cryptography.MD5_Encrypt(pass);
            }


            DBAccess.RunSQL("UPDATE Port_Emp SET Pass='" + pass + "'");
            #endregion 处理密码加密.
        }
        public static void ReCreateView()
        {
            //抄送规则.
            BP.WF.Template.CCRole cc = new CCRole();
            cc.CheckPhysicsTable();

            BP.WF.CCList list = new CCList();
            list.CheckPhysicsTable();

            if (DBAccess.IsExitsTableCol("WF_GenerWorkerList", "FK_NodeText") == true)
            {
                DBAccess.RenameTableField("WF_GenerWorkerList", "FK_NodeText", "NodeName");
                DBAccess.RenameTableField("WF_GenerWorkerList", "FK_EmpTex", "EmpName");
                DBAccess.RenameTableField("WF_GenerWorkerList", "FK_DeptT", "DeptName");
            }

            if (DBAccess.IsExitsObject("WF_EmpWorks") == true)
                DBAccess.RunSQL("DROP VIEW WF_EmpWorks");

            if (DBAccess.IsExitsObject("V_WF_Delay") == true)
                DBAccess.RunSQL("DROP VIEW V_WF_Delay");

            if (DBAccess.IsExitsObject("V_FlowStarter") == true)
                DBAccess.RunSQL("DROP VIEW V_FlowStarter");

            if (DBAccess.IsExitsObject("V_FlowStarterBPM") == true)
                DBAccess.RunSQL("DROP VIEW V_FlowStarterBPM");

            if (DBAccess.IsExitsObject("V_TOTALCH") == true)
                DBAccess.RunSQL("DROP VIEW V_TOTALCH");

            if (DBAccess.IsExitsObject("V_TOTALCHYF") == true)
                DBAccess.RunSQL("DROP VIEW V_TOTALCHYF");

            if (DBAccess.IsExitsObject("V_TotalCHWeek") == true)
                DBAccess.RunSQL("DROP VIEW V_TotalCHWeek");

            if (DBAccess.IsExitsObject("WF_Todolist") == true)
                DBAccess.RunSQL("DROP VIEW WF_Todolist");

            string prix = "";
            if (SystemConfig.CCBPMRunModel == CCBPMRunModel.SAAS)
                prix = "";

            //执行必须的sql.
            string sqlscript = "";
            //执行必须的sql.
            switch (BP.Difference.SystemConfig.AppCenterDBType)
            {
                case DBType.Oracle:
                case DBType.DM:
                case DBType.KingBaseR3:
                case DBType.KingBaseR6:
                case DBType.GBASE8CByOracle:
                    sqlscript = BP.Difference.SystemConfig.CCFlowAppPath + "WF/Data/Install/SQLScript/InitView_Ora" + prix + ".sql";
                    break;
                case DBType.MSSQL:
                case DBType.Informix:
                    sqlscript = BP.Difference.SystemConfig.CCFlowAppPath + "WF/Data/Install/SQLScript/InitView_SQL" + prix + ".sql";
                    break;
                case DBType.MySQL:
                    sqlscript = BP.Difference.SystemConfig.CCFlowAppPath + "WF/Data/Install/SQLScript/InitView_MySQL" + prix + ".sql";
                    break;
                case DBType.PostgreSQL:
                case DBType.UX:
                case DBType.HGDB:
                    sqlscript = BP.Difference.SystemConfig.CCFlowAppPath + "WF/Data/Install/SQLScript/InitView_PostgreSQL" + prix + ".sql";
                    break;
                default:
                    break;
            }
            DBAccess.RunSQLScript(sqlscript);
        }

    }
}
